<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <TaskTitle :title-name="titleName" icon-name="to do" color="blue" />
    <div class="list-container">
      <div class="progress-container">
        <TitleSecondary title="审批流程图" />
        <ProgressStaus />
      </div>
      <ProgressGraph :data="data" />
      <TitleSecondary title="基本信息" />
      <FormPriceBasicInfoLists :form-info="formInfo" :plan-type="planType" />
      <TitleSecondary title="价格变更明细" />
      <div
        id="screenfull-container"
        ref="screenfull"
        class="container"
        :class="{ 'screenfull-container': isFullscreen }"
      >
        <ButtonGroup
          v-if="buttons.length && !isFullscreen"
          class="button-container"
          :options="buttons"
          @click="handleButtonClick"
        />
        <ScreenfullHead />
        <SearchDetailFormPrice
          ref="form"
          :has-export="false"
          @search="onSearch(true)"
        />
        <p-table
          :custom-header-row="customHeaderRowMinxin"
          row-key="id"
          class="table-box"
          :columns="columns"
          bordered
          :scroll="{ x: '100%', y: isFullscreen ? 'calc(100vh - 300px' : 300 }"
          :pagination="false"
          :data-source="totalData"
          :row-selection="rowSelectionMixin"
          size="middle"
          @change="handleTableChange"
        >
        </p-table>
        <DialogFiledFilter
          :visible.sync="visibleFiled"
          :get-container="getContainer"
          :fileds="fileds"
          :local-key="localKey"
          :show.sync="filedShowKeys"
          :fixed.sync="filedFixedKeys"
        />
      </div>
      <TitleSecondary v-if="hasEdit" title="审批信息" />
      <ApprovalPriceInformation v-if="hasEdit" ref="approval" />
      <!-- <TitleSecondary
        title="操作日志"
        :icon="iconStaus"
        @change="handleChangeIcon"
      />
      <ProgressPortrait v-show="isShowProgressPortrait" :logs="logs" /> -->
      <ProgressLog :list="logs" />
      <BottomLine />
    </div>
    <ButtonGroup
      class="footer"
      :options="filterButtons"
      @click="handleButtonClick"
    />
    <DialogPriceTransfer
      :visible.sync="visibleTransfer"
      :price-id="priceId"
      @change="onClose"
    />
    <DialogBpForecastRelationList
      :value="currentRowInfo.value"
      :visible="visibleBpId"
      :time-range="timeRange"
      :is-edit="false"
      :condition="{
        relationId: currentRowInfo.row && currentRowInfo.row.bpRelationId,
        mforecastSalesId:
          currentRowInfo.row && currentRowInfo.row.mforecastSalesId,
      }"
      @cancel="(val) => (visibleBpId = val)"
      @change="(e) => confirmDialog(e)"
    />
    <DialogRpRelationList
      :value="currentRowInfo.value"
      :visible="visibleRpId"
      :time-range="timeRange"
      :is-edit="false"
      :condition="{
        relationId: currentRowInfo.row && currentRowInfo.row.rpRelationId,
        mforecastSalesId:
          currentRowInfo.row && currentRowInfo.row.mforecastSalesId,
      }"
      @cancel="(val) => (visibleRpId = val)"
      @change="(e) => confirmDialog(e)"
    />
  </p-drawer>
</template>

<script>
import ProgressLog from '@/components/task/ProgressLog.vue';
import FormPriceBasicInfoLists from '@/components/task/FormPriceBasicInfoLists.vue';
import ProgressGraph from '@/components/task/ProgressGraph.vue';
import ProgressStaus from '@/components/task/ProgressStaus.vue';
// import TablePlanDetail from '@/components/task/TablePlanDetail.vue';
import ApprovalPriceInformation from '@/components/task/ApprovalPriceInformation.vue';
import DialogPriceTransfer from '@/components/dialog/DialogPriceTransfer.vue';
import DialogBpForecastRelationList from '@/components/dialog/DialogBpForecastRelationList.vue';
import DialogRpRelationList from '@/components/dialog/DialogRpRelationList.vue';
import SearchDetailFormPrice from '@/components/search/SearchDetailFormPrice.vue';
import DialogFiledFilter from '@/components/dialog/DialogFiledFilter.vue';
import ColumnsTooltip from '../components/columnsTooltip.vue';

import { postPriceChangeApprove, postExport } from '@/api/price';
import DrawerMixin from './mixin';
import PriceChangeMixin from '@/views/price-change/components/mixin';
import { downloadFile } from '@/utils/index.js';
import Decimal from 'decimal.js';
import screenfull from '@/utils/screenfull';

export default {
  components: {
    FormPriceBasicInfoLists,
    // TablePlanDetail,
    // sdfsdfsdf
    ProgressGraph,
    ProgressStaus,
    ApprovalPriceInformation,
    DialogPriceTransfer,
    ProgressLog,
    DialogBpForecastRelationList,
    DialogRpRelationList,
    SearchDetailFormPrice,
    DialogFiledFilter,
  },
  mixins: [DrawerMixin, PriceChangeMixin],

  props: {
    dateArr: {
      type: Array,
      default: () => [],
    },
    // data: {
    //   type: Array,
    //   default: () => [],
    // },
    formData: {
      type: Array,
      default: () => [],
    },
    visibleAudit: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      iconStaus: 'down', //icon图片up、down的切换
      planDetailList: [],
      visibleTransfer: false,
      checkedGroups: {},
      groups: {},
      isEdit: false,
      dataSource: [],
      currentRowInfo: {},
      visibleBpId: false,
      visibleRpId: false,
      dataSourceFilter: [],
      isFullscreen: false,
      filedShowKeys: [],
      visibleFiled: false,
      hideKeys: 'selection',
      filedFixedKeys: [],
    };
  },
  computed: {
    fileds() {
      return this.defaultCoulumns;
    },
    columns() {
      let columns = this.defaultCoulumns.filter((item) => !item.isHide);
      if (this.filedShowKeys.length) {
        columns = columns.filter((item) => {
          return (
            item.required ||
            this.filedShowKeys.includes(item.dataIndex) ||
            item.noOperate
          );
        });
      }
      const left = [],
        right = [];
      columns.forEach((item) => {
        if (
          item.fixed === 'left' ||
          this.filedFixedKeys.includes(item.dataIndex)
        ) {
          console.log('item: ', item);
          left.push({ ...item, fixed: 'left' });
        } else {
          right.push(item);
        }
      });
      return [...left, ...right];
    },
    defaultCoulumns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          fixed: 'left',
          noOperate: true,
          // customRender(t, r, index) {
          //   return parseInt(index) + 1;
          // },
          customRender: (t, r, index) => {
            if (this.totalAllIndex.includes(index)) {
              return {
                children: (
                  <div style="display: flex;justify-content: flex-start;">
                    汇总
                  </div>
                ),
                attrs: {
                  colSpan: this.colIndex,
                },
              };
            }
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: 'M+9关系ID',
          dataIndex: 'm9RelationId',
          key: 'm9RelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '关联RP关系ID',
          dataIndex: 'rpRelationId',
          key: 'rpRelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <InputSearch
                value={{ key: value, label: value }}
                isEdit={false}
                isLink={true}
                vOn:search={() =>
                  this.openDialog('visibleRpId', {
                    value,
                    row,
                    index,
                    dataIndex: 'rpRelationId',
                  })
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '关联BP关系ID',
          dataIndex: 'bpRelationId',
          key: 'bpRelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <InputSearch
                value={{ key: value, label: value }}
                isEdit={false}
                isLink={true}
                vOn:search={() =>
                  this.openDialog('visibleBpId', {
                    value,
                    row,
                    index,
                    dataIndex: 'bpRelationId',
                  })
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '厂别',
          dataIndex: 'factoryCode',
          key: 'factoryCode',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.factoryOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'customerName',
          key: 'customerName',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '机种',
          dataIndex: 'modelInfoName',
          key: 'modelInfoName',
          width: 120,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} setWidth={'120px'} />
              </div>
            );
            return this.customRender(children, index);
          },
          // customRender: (value, row, index) => {
          //   const children = (
          //     <div>
          //       <InputSearch value={value} isEdit={false} />
          //     </div>
          //   );
          //   return this.customRender(children, index);
          // },
        },
        {
          align: 'center',
          title: 'Model Name',
          dataIndex: 'modelName',
          key: 'modelName',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '料号',
          dataIndex: 'materialCode',
          key: 'materialCode',
          isHide: this.hideKeys.includes('relationId'),
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '生产地',
          width: 80,
          dataIndex: 'manufactureArea',
          isHide: this.hideKeys.includes('relationId'),
          key: 'manufactureArea',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.productionPlaceOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '应用别',
          dataIndex: 'application',
          key: 'application',
          width: 80,
          isHide: this.hideKeys.includes('relationId'),
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.applicationOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '模切比',
          width: 80,
          dataIndex: 'modelCutRate',
          key: 'modelCutRate',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '形态',
          dataIndex: 'appearance',
          key: 'appearance',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.shapeOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户项目',
          dataIndex: 'item',
          key: 'item',
          width: 80,
          isHide: this.hideKeys.includes('relationId'),
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '内部项目',
          dataIndex: 'innerItem',
          key: 'innerItem',
          isHide: this.hideKeys.includes('relationId'),
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '类别',
          dataIndex: 'category',
          isHide: this.hideKeys.includes('relationId'),
          key: 'category',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.categoryOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '备注',
          width: 100,
          dataIndex: 'remark',
          isHide: this.hideKeys.includes('relationId'),
          key: 'remark',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
      ];
      if (this.dateArr.length) {
        this.dateArr.forEach((date, i) => {
          columns.push({
            align: 'center',
            title: date,
            dataIndex: `priceMonth${i}`,
            width: 180,
            noOperate: true,
            ellipsis: true,
            children: [
              {
                align: 'center',
                title: 'BP',
                dataIndex: `bpPriceMonth${date}`,
                key: `bpPrice${date}`,
                width: 100,
              },
              {
                align: 'center',
                title: 'RP',
                dataIndex: `rpPriceMonth${date}`,
                key: `rpPrice${date}`,
                width: 100,
              },
              {
                align: 'center',
                title: 'M+9',
                dataIndex: `priceMonth${date}`,
                key: `price${date}`,
                width: 100,
              },
              {
                align: 'center',
                title: '最新价格',
                dataIndex: `newPriceMonth${date}`,
                key: `newPrice${date}`,
                width: 100,
                ellipsis: true,
                scopedSlots: {
                  customRender: `newPriceMonth${date}`,
                },
                customRender: (value, row, index) => {
                  // console.log(value, row, index,'value, row, index-===123')
                  // let totalKeys = Object.keys(row).filter((item) =>
                  //   item.includes(`${date}`)
                  // );

                  // // console.log(totalKeys,'totalKeys -===123')

                  // let isDisabled = !totalKeys.length

                  const children = (
                    <div>
                      <p-tooltip title={value}>
                        <InputTable
                          isEdit={this.isEdit}
                          isNewPrice={true}
                          value={value}
                          vOn:change={(e) =>
                            this.handleInputChange(
                              e,
                              value,
                              row,
                              index,
                              `newPriceMonth${date}`
                            )
                          }
                        />
                      </p-tooltip>
                    </div>
                  );
                  return {
                    children,
                  };
                },
              },
            ],
          });
        });
      }
      // console.log(columns);
      return columns;
    },

    buttons() {
      return [
        {
          key: 'exportExcel',
          label: '导出',
        },
        {
          key: 'show',
          label: '显示字段',
        },
        {
          key: 'screenfull',
          label: '全屏显示',
        },
      ];
    },
    timeRange() {
      return [this.formInfo.startTime, this.formInfo.endTime];
    },
    totalData() {
      if (!this.dataSourceFilter.length) return [];
      const totalKeys = Object.keys(this.dataSourceFilter[0]).filter((item) =>
        item.includes('Month')
      );
      // console.log(totalKeys, 'keys')
      const obj = this.dataSourceFilter.reduce(
        (pre, cur) => {
          totalKeys.forEach((key) => {
            if (!pre[key]) {
              pre[key] = 0;
            }
            const numVal = new Decimal(pre[key]).plus(
              new Decimal(cur[key] || 0)
            );
            pre[key] = numVal.toFixed(2);
            // pre[key] += Number(cur[key]);
          });
          return pre;
        },
        { id: 'totalKey' }
      );
      return [
        ...this.dataSourceFilter,
        { ...this.dataSourceFilter[0], ...obj },
      ];
      // console.log(obj, '-----------------------')
    },
    totalAllIndex() {
      return this.totalData.reduce((pre, cur, index) => {
        if (cur.id === 'totalKey') {
          pre.push(index);
        }
        return pre;
      }, []);
    },
    disabledAgree() {
      const checkedLength = Object.keys(this.checkedGroups).filter(
        (el) => this.checkedGroups[el]
      ).length;
      const groupsLenght = Object.keys(this.groups).length;
      if (checkedLength === 0) return true;
      return checkedLength !== groupsLenght;
    },
    disabledRefuse() {
      const checkedLength = Object.keys(this.checkedGroups).filter(
        (el) => this.checkedGroups[el]
      ).length;
      return checkedLength < 1;
    },
    isShowProgressPortrait() {
      return this.iconStaus === 'up';
    },
    footerButtons() {
      return [
        {
          key: 'submit',
          type: 'primary',
          label: '提交',
          auth: true,
        },
        {
          key: 'transfer',
          label: '转他人处理',
          auth: true,
        },
        {
          key: 'close',
          label: '返回',
        },
      ];
    },
  },
  watch: {
    formData: {
      handler(val) {
        if (!val) return;
        this.searchTableList();
      },
    },
    dataSource: {
      handler(val) {
        this.onSearch();
      },
      immediate: true,
    },
    // dateArr:{
    //   handler(val){

    //   }
    // }
  },
  created() {},
  mounted() {
    this.onSearch();
    screenfull.onchange((e) => {
      this.isFullscreen = screenfull.isFullscreen;
    });
  },
  methods: {
    async screenfullCallback() {
      const ele = this.$refs.screenfull;
      if (screenfull.isEnabled) {
        await screenfull.toggle(ele, { navigationUI: 'hide' });
      }
    },
    getContainer() {
      return document.getElementById('screenfull-container');
    },
    showCallback() {
      this.visibleFiled = true;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    onSearch(isSearch) {
      console.log('isSearch: ', isSearch);
      if (!this.$refs.form) return;
      if (!isSearch) {
        this.$refs.form.handleReset();
        return;
      }
      const form = (this.$refs.form && this.$refs.form.form) || {};
      const isEmpty = (val) => !val;
      console.log('isEmpty: ', isEmpty);

      // 应用别
      const isApplication = (val) =>
        isEmpty(form.application) || form.application === val;
      // 形态
      const isAppearance = (val) =>
        isEmpty(form.appearance) || form.appearance === val;
      // 生产地
      const isManufactureArea = (val) =>
        isEmpty(form.manufactureArea) || form.manufactureArea === val;
      // Model Name
      const isModelName = (val) =>
        isEmpty(form.modelName) || val?.includes(form.modelName);
      // 机种
      const isModelNumber = (val) =>
        isEmpty(form.modelInfoName) || val?.includes(form.modelInfoName);
      // 客户简称 customerCode
      const isCustomerCode = (val) =>
        isEmpty(form.customerName) || val?.includes(form.customerName);
      this.dataSourceFilter = this.dataSource.filter((item) => {
        return (
          // isPlanSalesId(item.planSalesId) &&
          isApplication(item.application) &&
          isAppearance(item.appearance) &&
          isManufactureArea(item.manufactureArea) &&
          isModelName(item.modelName) &&
          isModelNumber(item.modelInfoName) &&
          isCustomerCode(item.customerName)
        );
      });
      console.log('this.dataSourceFilter: ', this.dataSourceFilter);
    },
    openDialog(dialog, rowInfo) {
      this[dialog] = true;
      this.currentRowInfo = rowInfo;
      console.log('this.currentRowInfo: ', this.currentRowInfo);
    },
    getMathVal(data) {
      let resultAll = [
        this.getMathType(data, 'newPrice'),
        this.getMathType(data, 'bpPrice'),
        this.getMathType(data, 'rpPrice'),
        this.getMathType(data, 'price'),
      ];
      let result = [];
      resultAll?.forEach((item) => {
        if (item.length > result.length) {
          result = item;
        }
      });
      return result;
    },
    getMathType(data, type) {
      let result = [];
      for (let i = 0; i < data?.length; i++) {
        if (!data[i][type]) {
          continue;
        }
        let val = Object.keys(JSON.parse(data[i][type]));
        if (val.length > result.length) {
          result = val;
        }
      }
      return result;
    },
    async exportExcelCallback() {
      const data = JSON.parse(JSON.stringify(this.totalData));
      data.pop();
      const res = await postExport({
        priceChangeDetails: data,
        endTime: this.formInfo.endTime,
        startTime: this.formInfo.startTime,
      });
      await downloadFile(res.data, res.filename || '价格明细.xls');
    },
    searchTableList() {
      const data = this.proessData(this.formData) || [];
      this.dataSource = data;
      // this.dataSource = this.calcAddTotal(data);
      // console.log(this.dataSource, 'this.dataSource2');
    },

    handleTableCheckedChange(checkedGroups, groups) {
      this.checkedGroups = checkedGroups;
      this.groups = groups;
    },
    onClose() {
      this.$emit('update:visible', false);
      this.$emit('change-currstatus', '1');
      this.$emit('fresh');
    },
    closeCallback() {
      this.onClose();
    },
    async submitCallback() {
      // console.log('??????!!!!!!???', this.processId);
      const data = this.$refs.approval?.form || {};
      if (typeof data.approveStatus !== 'boolean') {
        this.$message.error('请先进行审批！');
        return;
      }
      if (data.approveStatus === false && !data.approveOpinion) {
        this.$message.error('请填写审批意见！');
        return;
      }
      await postPriceChangeApprove({
        ...data,
        priceId: this.priceId,
        processId: this.processId,
      });
      this.$message.success('提交成功！');
      this.closeCallback();
    },
    transferCallback() {
      this.visibleTransfer = true;
    },
  },
};
</script>

<style lang="less" scoped>
.poros-tabs {
  min-height: 500px;
}
.footer {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #e5e6e9;
}
.list-container {
  height: calc(100vh - 110px);
  overflow-y: scroll;
  position: relative;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  padding: 10px 24px;
}

/deep/ .poros-drawer-body {
  min-width: 1136px;
  height: 100%;
  padding: 0;
}
.progress-container {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.table-box {
  margin: 10px 0 20px 0;
}
.button {
  padding: 7px 0;
}
.screenfull-container {
  background: #fff;
  padding: 20px;
}
.container {
  margin-bottom: 20px;
}
</style>
